import pymysql
from datetime import datetime

from stock_control.my_tushare import get_sell_price


class PositionDB:
    def __init__(self):
        # 创建一个连接数据库的对象
        self.conn = pymysql.connect(
            host='localhost',  # 连接的数据库服务器主机名
            port=3306,  # 数据库端口号
            user='root',  # 数据库登录用户名
            passwd='123456',
            db='stock',  # 数据库名称
            charset='utf8',  # 连接编码
            cursorclass=pymysql.cursors.DictCursor
        )
        # 使用cursor()方法创建一个游标对象，用于操作数据库
        self.cur = self.conn.cursor()

    # 查看当前持仓情况
    def view_position(self):
        sql = "SELECT * FROM t_position"
        self.cur.execute(sql)
        result = self.cur.fetchall()  # 显示所有结果
        return result

    # 特殊查询-查询一个策略的持仓
    def search_by_strategy(self, strategy_name):
        sql = "SELECT * FROM t_position where strategy_name = %s"
        self.cur.execute(sql, strategy_name)
        result = self.cur.fetchall()  # 显示所有结果
        return result

    # 特殊查询-查询一个股票的持仓
    def search_by_stock(self, stock_id):
        sql = "SELECT * FROM t_position where stock_id = %s"
        self.cur.execute(sql, stock_id)
        result = self.cur.fetchall()  # 显示所有结果
        return result

    # 更新当天持仓情况,today格式“YYYYMMDD”
    def update_position(self, today):
        sql = "SELECT * FROM t_position"
        self.cur.execute(sql)
        res = self.cur.fetchone()
        while res:
            pid = res['p_id']
            ts_code = res['stock_id']
            t_price = get_sell_price(ts_code, today)
            upd = "UPDATE t_position set today_price = %s where p_id = %s"
            try:
                self.cur.execute(upd, (t_price, pid))  # 执行sql
                self.conn.commit()  # 增删改操作完数据库后，需要执行提交操作
            except:
                # 发生错误时回滚
                self.conn.rollback()
            res = self.cur.fetchone()
        self.conn.close()  # 记得关闭数据库连接

    # 插入新买入的股票
    def insert(self, sql, value):
        try:
            self.cur.execute(sql, value)  # 执行sql
            self.conn.commit()  # 增删改操作完数据库后，需要执行提交操作
            return True
        except:
            # 发生错误时回滚
            self.conn.rollback()
            return False

    # 插入新买入的股票信息 value参数为元组类型
    def insert_position(self, value):
        sql = "insert into t_position(strategy_name,stock_id,stock_name,stock_num,buy_time,buy_price,today_price)"\
              "values (%s,%s,%s,%s,%s,%s,%s)"
        flag = self.insert(sql, value)
        self.conn.close()
        if flag:
            return "持仓记录成功"
        else:
            return "持仓记录失败"

    # 删除某策略的某股票
    def delete(self, strategy_name, stock_id):
        sql = "DELETE FROM t_position where strategy_name = %s and stock_id = %s"
        try:
            self.cur.execute(sql, (strategy_name, stock_id))  # 执行sql
            self.conn.commit()  # 增删改操作完数据库后，需要执行提交操作
        except:
            # 发生错误时回滚
            self.conn.rollback()
        self.conn.close()


if __name__ == '__main__':
    p = PositionDB()
    # p.delete()已测试没问题
    # print(p.insert_log(('test1', '2', 'stockname2', '100', '2000-01-14', '1.2', '2.2')))
    # res = p.view_position()
    # res = p.search_by_stock('2')
    res = p.search_by_strategy('test')
    print(res)

